package org.iwidget.desktop.core.bsf;

import java.awt.Toolkit;
import java.awt.datatransfer.*;

/**
 *
 * @author Muhammad Hakim A
 */
public class IwidgetClipboardBSF implements ClipboardOwner {

    public IwidgetClipboardBSF() {
    }

    public void lostOwnership(Clipboard clipboard, Transferable transferable) {
    }

    public void set(String data) {
        SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
            try {
                sm.checkSystemClipboardAccess();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        Toolkit tk = Toolkit.getDefaultToolkit();
        StringSelection st = new StringSelection(data);
        Clipboard cp = tk.getSystemClipboard();
        cp.setContents(st, this);
    }

    public String get() {
        try {
            Transferable contents;
            SecurityManager sm = System.getSecurityManager();
            if (sm != null) {
                try {
                    sm.checkSystemClipboardAccess();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            Toolkit tk = Toolkit.getDefaultToolkit();
            Clipboard cp = tk.getSystemClipboard();
            contents = cp.getContents(this);
            if (!contents.isDataFlavorSupported(DataFlavor.stringFlavor)) {
                return null;
            }
            return (String) contents.getTransferData(DataFlavor.stringFlavor);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
